package com.ukao.steward.base;

import android.content.Context;
import android.content.DialogInterface;
import android.content.res.Resources;
import android.graphics.Point;
import android.os.Bundle;
import android.support.annotation.ColorRes;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.TextView;

import com.ukao.steward.R;
import com.ukao.steward.retrofit.ApiClient;
import com.ukao.steward.retrofit.ApiStores;
import com.ukao.steward.util.KeyBoardUtil;
import com.ukao.steward.util.SpanUtils;
import com.ukao.steward.util.T;
import com.ukao.steward.widget.ZProgressHUD;

import org.greenrobot.eventbus.EventBus;
import org.zackratos.ultimatebar.UltimateBar;

import me.yokeyword.fragmentation.SupportFragment;
import rx.Observable;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;
import rx.subscriptions.CompositeSubscription;

import static android.content.Context.WINDOW_SERVICE;
import static com.ukao.steward.base.BaseActivity.DESIGN_WIDTH;

/**
 * Created by ukaodev on 2017/5/24.
 */

public  abstract class BaseFragment extends SupportFragment  implements DialogInterface.OnDismissListener {
    public static   String ARG_PARAM1 = "param1";
    public static  String  ARG_PARAM2 = "param2";
    protected Resources resources;
    protected OnFragmentOpenDrawerListener mOpenDraweListener;
    private ZProgressHUD progressDialog;
    protected  boolean  isVisible;


    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        if (context instanceof OnFragmentOpenDrawerListener) {
            mOpenDraweListener = (OnFragmentOpenDrawerListener) context;
        }

    }
    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        resources= getActivity().getResources();
        if (useEventBus()) {
            EventBus.getDefault().register(this);
        }
        resetDensity();
    }



    protected void initToolbarNav(ImageView toolbar) {
        toolbar.setImageResource(R.drawable.ic_menu_white_24dp);
        toolbar.setOnClickListener(v -> {
            if (mOpenDraweListener != null) {
                mOpenDraweListener.onOpenDrawer();
            }
        });
    }
    public interface OnFragmentOpenDrawerListener {
        void onOpenDrawer();
    }


    /**
     * 可见
     */
    @Override
    public void onSupportVisible() {
        super.onSupportVisible();
        isVisible=true;
    }

    /**
     * 不可见
     */
    @Override
    public void onSupportInvisible() {
        super.onSupportInvisible();
        isVisible=false;
        KeyBoardUtil.hideKeyboard(_mActivity);
    }
    public void resetDensity(){
        Point size = new Point();
        ((WindowManager)_mActivity.getSystemService(WINDOW_SERVICE)).getDefaultDisplay().getSize(size);
        getResources().getDisplayMetrics().xdpi = size.x/DESIGN_WIDTH*72f;
    }

    protected  boolean useEventBus(){
        return false;
    }

    protected abstract void initView();


    protected void initListener() {

    }


    public void finish(){
        KeyBoardUtil.hideKeyboard(_mActivity);
        pop();
    }



    protected String getText(TextView txt) {
        String message;
        if (txt!=null){
             message = txt.getText().toString().trim();
        }else{
            message="";
        }

        return message;
    }




    protected   CharSequence  mustSpanText(String  hite ){
        CharSequence  mCharSequence=new SpanUtils().append(hite).append("*").setForegroundColor(getColors(R.color.pink)).create();
        return mCharSequence;
    }


    // 设置状态栏颜色
    public void setStatusBarTintColor(int resId) {
        UltimateBar ultimateBar = new UltimateBar(_mActivity);
        ultimateBar.setColorBar(ContextCompat.getColor(_mActivity,R.color.colorPrimary));

    }

    public void setColorBarForDrawerColor(int resId) {
        UltimateBar ultimateBar = new UltimateBar(_mActivity);
        ultimateBar.setColorBarForDrawer(ContextCompat.getColor(_mActivity,resId));

    }






    protected void initGalleryRecyclerView(RecyclerView recyclerViews) {
        recyclerViews.setHasFixedSize(true);
        LinearLayoutManager mLinearLayoutManager = new LinearLayoutManager(_mActivity);
        recyclerViews.setLayoutManager(mLinearLayoutManager);
        mLinearLayoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);

    }

    protected void initLinearRecyclerView(RecyclerView recyclerViews ) {
        recyclerViews.setHasFixedSize(true);
        recyclerViews.setLayoutManager(new LinearLayoutManager(_mActivity));
    }

    protected void initGridRecyclerView(RecyclerView recyclerViews, int num) {
        recyclerViews.setHasFixedSize(true);
        recyclerViews.setLayoutManager(new GridLayoutManager(_mActivity, num));

    }



    @Override
    public void onDetach() {
        super.onDetach();
        mOpenDraweListener = null;
    }


//    @Override
//    public void setUserVisibleHint(boolean isVisibleToUser) {
//        super.setUserVisibleHint(isVisibleToUser);
//        if (isResumed()) {
//            if(isVisibleToUser){
//                JAnalyticsInterface.onPageStart(getActivity(),this.getClass().getCanonicalName());
//            }else {
//                JAnalyticsInterface.onPageEnd(getActivity(),this.getClass().getCanonicalName());
//            }
//        }
//    }
//
//    @Override
//    public void onHiddenChanged(boolean hidden) {
//        super.onHiddenChanged(hidden);
//
//        if(hidden){
//            JAnalyticsInterface.onPageEnd(getActivity(),this.getClass().getCanonicalName());
//        }else {
//            JAnalyticsInterface.onPageStart(getActivity(),this.getClass().getCanonicalName());
//        }
//    }
//
//    @Override
//    public void onResume() {
//        super.onResume();
//        if (!isHidden() && getUserVisibleHint()) {
//            JAnalyticsInterface.onPageStart(getActivity(),this.getClass().getCanonicalName());
//        }
//    }
//
//    @Override
//    public void onPause() {
//        super.onPause();
//        if (!isHidden() && getUserVisibleHint()) {
//            JAnalyticsInterface.onPageEnd(getActivity(),this.getClass().getCanonicalName());
//        }
//    }



    public  int  getColors( @ColorRes int id){
        return   ContextCompat.getColor(_mActivity,id);

    }



    public ZProgressHUD showProgressDialog() {
        if (progressDialog==null){
            progressDialog= new ZProgressHUD(_mActivity);
        }
        progressDialog.setMessage("Loading ...");
        progressDialog.setOnDismissListener(this);
        progressDialog.show();


        return progressDialog;
    }

    public ZProgressHUD showProgressDialog(String message) {
        if (progressDialog==null){
            progressDialog = ZProgressHUD.getInstance(_mActivity);
        }
        progressDialog.setMessage(message);
        progressDialog.show();
        return progressDialog;
    }

    public void dismissProgressDialog() {
        if (progressDialog != null && progressDialog.isShowing()) {
            // progressDialog.hide();会导致android.view.WindowLeaked
            progressDialog.dismiss();
        }
    }

    public  void  showErrors(String  error){
        T.show(error);
    }


    private CompositeSubscription mCompositeSubscription;

    public ApiStores apiStores() {
        return ApiClient.retrofit().create(ApiStores.class);
    }

    public void addSubscription(Observable observable, Subscriber subscriber) {
        if (mCompositeSubscription == null) {
            mCompositeSubscription = new CompositeSubscription();
        }
        mCompositeSubscription.add(observable
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(subscriber));
    }

    public void onUnsubscribe() {

        //取消注册，以避免内存泄露
        if (mCompositeSubscription != null && mCompositeSubscription.hasSubscriptions())
            mCompositeSubscription.unsubscribe();
    }


    @Override
    public void onDismiss(DialogInterface dialog) {

    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        onUnsubscribe();
        mCompositeSubscription=null;
        if (useEventBus()) {
            EventBus.getDefault().unregister(this);
        }

    }
}
